package com.py.gs.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {


	/**
	 * 从网络Url中下载文件
	 * 
	 * @param urlStr
	 * @param fileName
	 * @param savePath
	 * @throws IOException
	 */
	public static void downLoadFromUrl(String urlStr, int timeout, String fileName, String savePath) throws IOException {
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 设置超时间
		conn.setConnectTimeout(timeout);

		// 文件保存位置
		File saveDir = new File(savePath);
		if (!saveDir.exists()) {
			saveDir.mkdir();
		}
		File file = new File(saveDir + File.separator + fileName);
		try (InputStream in = conn.getInputStream();
				FileOutputStream out = new FileOutputStream(file)) {
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
		}
	}

	public static void main(String[] args) {
		try {
			downLoadFromUrl("http://172.18.90.111:8080/cfg/xml.zip", 500, "xml.zip", "C:\\Users\\HP\\Desktop\\");
			System.out.println("download success");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
